//
//  HOReplyViewController.m
//  微度报修
//
//  Created by foguo-mac-1 on 6/27/16.
//  Copyright © 2016 WeiDu. All rights reserved.
//

#import "HOReplyViewController.h"
#import "HOConstants.h"
#import "HOEditView.h"
#import "HOReplyListViewController.h"
#import "HOStatusTableViewCell.h"
#import "HOReportOrderEntity.h"
#import "HOUtils.h"
#import "HOStatusEntity.h"
#import "HOStaticDataMgr.h"
#import "HOUploadImageView.h"
#import "HORecordView.h"
#import "HORecordMgr.h"
#import "HOExtraAssistantEntity.h"

@interface HOReplyViewController ()<HOEditViewDelegate>
{
	
}
@property(nonatomic, retain)HOEditView *replyEditView;
@property(nonatomic, retain)HOReportOrderEntity *orderEntity;
@property(nonatomic, assign)HO_REPORT_ORDER_STATUS status;
@end

@implementation HOReplyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
	[self initTableView];
	[self initSubviews];

	[self initTableViewFooterViewWithTitle:NSLocalizedString(@"回复信息", @"发表回复信息")];
	[self initMediaViewOnlyImageDiaplay];
	[self registerTapGesture];
	[self registerKeyboard];
}

- (void)initSubviews
{
	self.replyEditView = [[[HOEditView alloc] initWithFrame:CGRectMake(0,
																	  0,
																	  self.view.frame.size.width,
																	  80)] autorelease];
	self.replyEditView.limitedCount = 120;
	self.replyEditView.delegate = self;
	self.replyEditView.layer. cornerRadius = 0;
	self.replyEditView.layer.borderWidth = [HOUtils defaultOnePixelConversion];
	[self.replyEditView.layer setMasksToBounds:YES];
	[self.replyEditView setPlaceHolder:NSLocalizedString(@"维修描述", @"维修描述")];
	[self.replyEditView getTextView].returnKeyType = UIReturnKeySend;
}

- (void)hideKeyboard
{
	[[self.replyEditView getTextView] resignFirstResponder];
}

- (void)requestData
{
	if(!self.isCheckModal)
	{
		[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_CheckOrderStatus,
									  kHO_FIELD_OrderId:[NSNumber numberWithInt:self.entity.orderId]}];
	}
}

- (void)onKeyboardWillShow:(NSNotification *)notification
{
	[super onKeyboardWillShow:notification];
	if(!self.isCheckModal)
		[baseTableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
	[self hideKeyboard];
}
- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	[self setNavigationItemTitle:NSLocalizedString(@"回复信息", @"回复信息")];
	[self displayRightButtomItemWithTitle:NSLocalizedString(@"历史回复", @"历史回复")];
	self.status = self.entity.status;

	[self requestData];
	if(self.isCheckModal)
	{
		
		self.orderEntity = [[[HOReportOrderEntity alloc] init] autorelease];
		self.orderEntity.orderId = self.entity.orderId;
		self.orderEntity.status = self.entity.status;
		self.orderEntity.orderSN = self.entity.orderSN;
	}
	if(self.orderEntity.isUncompleted && self.status == HO_REPORT_ORDER_ACCEPTED)
	{
		self.status = HO_REPORT_ORDER_UNCOMPLETED;
	}
	[baseTableview reloadData];
}


- (void)rightButtonItemDidClick
{
	HOReplyListViewController *viewCtrl = [[HOReplyListViewController alloc] init];
	viewCtrl.orderId = self.orderEntity.orderId;
	viewCtrl.isExtraAssistant = self.isCheckModal;
	[self.navigationController pushViewController:viewCtrl animated:YES];
	[viewCtrl release];
}

- (void)dealloc
{
	self.replyEditView = nil;
	self.orderEntity = nil;
	[super dealloc];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
//	self.orderEntity.status = HO_EXTRA_ASS_ORDER_REPAIRED;
	[self hideKeyboard];
}

- (void)didClickFooterButton:(UIButton *)btn
{
	NSString *content = [self getTrimingCharaFromTextView:[self.replyEditView getTextView]];
	if(content.length == 0)
	{
		[self popupHintView:NSLocalizedString(@"请输入回复信息", @"请输入回复信息")];
		return;
	}
	
	self.view.userInteractionEnabled = NO;
	[self convertingVoice];
}

- (void)submit
{
	NSString *content = [self getTrimingCharaFromTextView:[self.replyEditView getTextView]];
	NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[self getMediaDic]];
	int myUserId =  [[[HOStaticDataMgr sharedInstance] getUserInfo] getUserId];
	if(self.isCheckModal)
	{
		[dic setObject:kHO_ACTION_AddExternalComment forKey:kHO_FIELD_Action];
	}
	else
	{
		[dic setObject:kHO_ACTION_AddComment forKey:kHO_FIELD_Action];
	}
	[dic setObject:content forKey:kHO_FIELD_Content];
	[dic setObject:[NSNumber numberWithInt:myUserId] forKey:kHO_FIELD_ReplyUserId];
	[dic setObject:[NSNumber numberWithInt:self.entity.orderId] forKey:kHO_FIELD_OrderId];
	[dic removeObjectForKey:kHO_FIELD_isReSubmit];
	[self sendRequestWithParams:dic];
}

#pragma mark - -- UITableViewDelegate/UITableViewDataResource implement methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(self.isCheckModal)
	{
		return 80;
	}
	else
	{
		if(indexPath.section == 0)
			return 44;
		else if(indexPath.section == 1)
			return 80;
		else if(indexPath.section == 2)
		{
			return [self getPhotoViewHeight];
		}
	}
	return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	if(self.isCheckModal)
		return 1;
    return 3;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	if(section == 0)
	{
		if(self.isCheckModal)
		{
			
			return 1;
//			HOExtraAssistantEntity * extraAssistantEntity = (HOExtraAssistantEntity *)self.entity;
//			if([extraAssistantEntity notNeedDeanCheck])
//			{
//				return 4;
//			}
//			else
//			{
//				return 5;
//			}
		}
		else
		{
			return 4;
		}
	}
	else if(section == 1)
		return 1;
	else if(section == 2)
		return 1;
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)] autorelease];
	if(section == 0)
	{
		UILabel *lbl = [[[UILabel alloc]
						 initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
												  0,
												  185,
												  30)] autorelease];
		lbl.text = @"订单号：3128";
		lbl.textColor = TEXT_COLOR_181818;
		lbl.font = [UIFont systemFontOfSize:15];
		lbl.text = [NSString stringWithFormat:@"%@%d", NSLocalizedString(@"订单号:", @"订单号:"),self.orderEntity.orderSN];
		
		if(self.isCheckModal)
		{
			lbl.text = [NSString stringWithFormat:@"%@%d    状态:", NSLocalizedString(@"订单号:", @"订单号:"),self.orderEntity.orderSN];
			UILabel *orderStatusLbl = [[[UILabel alloc] initWithFrame:CGRectMake(lbl.frame.size.width, 5, 100, 22)] autorelease];
			orderStatusLbl.font = [UIFont systemFontOfSize:14];
			NSString *statusStr = [HOUtils getDescribtionWithStatus:self.entity.status];
			if(self.entity.isUncompleted)
			{
				statusStr = @"未完成";
			}
			orderStatusLbl.text = statusStr;
			orderStatusLbl.textColor = [HOUtils getOrderColorWithStatus:self.entity.status];
			[view addSubview:orderStatusLbl];
		}
		
		[view addSubview:lbl];
	}
	return view;
}


- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	if(section == 0)
		return 30;
    return SECTION_PADDING / 4;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(indexPath.section == 0 && !self.isCheckModal)
	{
		static NSString *HOReplyTableViewCell = @"HOReplyTableViewCell1";
		HOStatusTableViewCell *cell = (HOStatusTableViewCell *)[tableView dequeueReusableCellWithIdentifier:HOReplyTableViewCell];
		if(cell == nil)
		{
			cell = [[[HOStatusTableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: HOReplyTableViewCell] autorelease];
			[cell initWithWidth:tableView.frame.size.width withHeight:40];
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		HOStatusEntity *statusEntity = nil;

		if(indexPath.row < [self.orderEntity.statusList count])
		{
			statusEntity = [self.orderEntity.statusList objectAtIndex:indexPath.row];
		}
//		HO_REPORT_ORDER_STATUS status = (indexPath.row + 1);
//		NSString *statusStr = [HOUtils getDescribtionWithStatus:status];
//		cell.statusLbl.text = statusStr;//
		if(indexPath.row == 0)
		{
			cell.statusLbl.text = NSLocalizedString(@"未受理", @"未受理");
			
		}
		else if(indexPath.row == 1)
		{
			cell.statusLbl.text = NSLocalizedString(@"已受理/未完成", @"已受理/未完成");
		}
		else if(indexPath.row == 2)
		{
			cell.statusLbl.text = NSLocalizedString(@"维修完成", @"维修完成");
		}
//		else if(indexPath.row == 3)
//		{
//			cell.statusLbl.text = NSLocalizedString(@"未完成", @"未完成");
//		}
		else if(indexPath.row == 3)
		{
			cell.statusLbl.text = NSLocalizedString(@"确认完成", @"确认完成");
		}

		
		if(statusEntity)
		{
			
			[cell setHightLight:indexPath.row < self.entity.status];
			
			cell.contentLbl.text = [NSString stringWithFormat:@"%@%@", NSLocalizedString(@"维修人:", @"维修人:"), statusEntity.repairmanName];
			cell.timeLbl.text = [HOUtils getDateFromTimeInterval:statusEntity.createTime * 1000];
			cell.contentLbl.hidden = NO;
			cell.timeLbl.hidden = NO;
		}
		
		return cell;

	}
	else if(indexPath.section == 1 || (self.isCheckModal && indexPath.section == 0))
	{
		static NSString *HOReplyTableViewCell = @"HOReplyTableViewCell";
		UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:HOReplyTableViewCell];
		if(cell == nil)
		{
			cell = [[[HOTableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: HOReplyTableViewCell] autorelease];
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		HOEditView *editView = (HOEditView *)[cell viewWithTag:1117];
		if(editView == nil)
		{
			self.replyEditView.tag = 1117;
			[cell.contentView addSubview:self.replyEditView];
		}
		return cell;
	}
	else if(indexPath.section == 2)
	{
		static NSString *HOTakePhotoTableViewCellIdentifier = @"HOTakePhotoTableViewCellIdentifier";
		HOTableViewCell *cell = (HOTableViewCell *)[tableView dequeueReusableCellWithIdentifier:HOTakePhotoTableViewCellIdentifier];
		if(cell == nil)
		{
			cell = [[[HOTableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: HOTakePhotoTableViewCellIdentifier] autorelease];
		}
		//	CGFloat cellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
		cell.textLabel.font = [UIFont systemFontOfSize:15];
		cell.textLabel.textColor = TEXT_COLOR_181818;
		cell.accessoryType = UITableViewCellAccessoryNone;
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		HOUploadImageView *uploadImgView = (HOUploadImageView *)[cell viewWithTag:114];
		if(uploadImgView == nil)
		{
			[cell.contentView addSubview:self.uploadImgView];
			uploadImgView.tag = 114;
			
			self.uploadImgView.frame = CGRectMake(0,
												  5,
												  self.view.frame.size.width,
												  self.singleImgWidth);
		}
		return cell;

	}
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
	if(indexPath.section == 0)
	{
		self.orderEntity.status = (HO_REPORT_ORDER_STATUS) indexPath.row + 1;
		[baseTableview reloadData];
	}
}
#pragma mark

- (HOEditTableViewCell *)tableView:(UITableView *)tableView cellForEditRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *AMBaseTableViewCellIdentifier = @"HOTableViewCell";
	HOEditTableViewCell *cell = (HOEditTableViewCell *)[tableView dequeueReusableCellWithIdentifier:AMBaseTableViewCellIdentifier];
	if(cell == nil)
	{
		cell = [[[HOEditTableViewCell alloc]
				 initWithStyle:UITableViewCellStyleDefault
				 reuseIdentifier: AMBaseTableViewCellIdentifier] autorelease];
	}
	return cell;
}
#pragma mark -- tool
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)didReceiveCommand:(NSString *)action data:(id)data
{
	if([action isEqualToString:kHO_CMD_ReceiveNotificationMessage])
	{
		NSDictionary *dic = [data objectForKey:kHO_FIELD_Extras];
		int type = [[dic valueForKey:kHO_FIELD_SendType] intValue];
		int orderId = [[dic valueForKey:kHO_FIELD_OrderId] intValue];
		if(type == HO_NC_TYPE_ORDER_ASSIGNED && orderId == self.orderEntity.orderId)
		{
			[self requestData];
		}
	}
}

- (void)cleanup
{
	self.replyEditView.getTextView.text = @"";
	[self.recordView cleanup];
	[self.uploadImgView cleanup];
	[super cleanup];
}


- (void)requestDidSuccessWithResponse:(HOBaseResponseEntity *)response
{
	if([response isEqualAction:kHO_ACTION_AddComment]
	   || [response isEqualAction:kHO_ACTION_AddExternalComment])
	{
		[self sendCommand:kHO_CMD_Report_Detail_Changed data:nil];
		[self popupHintView:NSLocalizedString(@"回复成功!", @"回复成功!")];
		[self cleanup];
	}
	else if([response isEqualAction:kHO_ACTION_CheckOrderStatus])
	{
		if(self.orderEntity == nil)
		{
			self.orderEntity = [[[HOReportOrderEntity alloc] init] autorelease];
			[self.orderEntity parseDic:response.dataNode];
			[baseTableview reloadData];
		}
	}
}

- (void)hintDidHide
{
	self.view.userInteractionEnabled = YES;
	[self goBack];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
